﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Caching;
using Microsoft.Practices.SharePoint.Common.Logging;
using Microsoft.Practices.SharePoint.Common.ServiceLocation;
using Microsoft.SharePoint.Administration;

namespace ITSP.SharePoint.CacheRefresh.Examples
{
    /// <summary>
    /// This is an example object that is used to show how to add an object to the 
    /// cache with a cache dependency based file watcher.
    /// </summary>
    public class CacheExampleObject
    {
        private static ILogger _logger = SharePointServiceLocator.GetCurrent().GetInstance<ILogger>();
        private CacheItemRemovedCallback cacheCallback;
        private const string CacheKey = "CacheExampleObject";
        public CacheExampleObject(SPWebApplication webApplication)
        {

            ExampleObject example = new ExampleObject();
            CacheRefreshManager cacheRefreshManager = new CacheRefreshManager(webApplication);
            SPCacheFileDependency dependency = cacheRefreshManager.GetCacheDependency("Example");
            if (dependency.Exists && dependency.Enabled)
            {
               _logger.TraceToDeveloper("Adding Example Object to Cache using Cache Key Example", 0, TraceSeverity.Verbose,Constants.Logging.DefaultLoggingCategory);
                cacheCallback = new CacheItemRemovedCallback(CacheExampleObjectCacheRefresh);
                HttpRuntime.Cache.Insert(CacheKey, example.XmlString, dependency, DateTime.Now.AddMinutes(120), System.Web.Caching.Cache.NoSlidingExpiration, CacheItemPriority.Normal, cacheCallback);
            }
            else
            {
                _logger.TraceToDeveloper("Cannot find Cache Configuration Item with a Key called Example.", 0, TraceSeverity.Verbose, Constants.Logging.DefaultLoggingCategory);
            }

        }

        /// <summary>
        /// Example Function which occurs when the cache item is flushed from the cache.
        /// </summary>
        /// <param name="key"></param>
        /// <param name="cacheObject"></param>
        /// <param name="reason"></param>
        public void CacheExampleObjectCacheRefresh(string key, object cacheObject, CacheItemRemovedReason reason)
        {
            Trace.WriteLine(String.Format("Cache Dependency Removed: {0} {1}", reason, key));
            _logger.TraceToDeveloper(String.Format("Example Object removed from Cache using Cache Key {0}. Reason for Removal: {1} ", key, reason), 0, TraceSeverity.Verbose, Constants.Logging.DefaultLoggingCategory);
        }
    }
}
